<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        :closable="false"
        show-icon
        type="warning">
      </el-alert>
      <div class="goodsCate" style="margin:10px 0;">
        选择商品分类：
        <el-cascader
          v-model="casderValue"
          :options="catesList"
          :props="catesProps"
          @change="casderHandleChange">
        </el-cascader>
      </div>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="paramsDialogVisible = true" :disabled="isBtnDisable" type="primary" size="mini">添加参数</el-button>
          <el-table
            :data="manyTableList"
            stripe
            border
            style="width: 100%">
            <el-table-column
              type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeTag(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  style="width: 120px"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#">
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button @click="editParams(scope.row.attr_id)" size="mini" type="primary" icon="el-icon-edit">修改</el-button>
                <el-button @click="delParams(scope.row.attr_id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="paramsDialogVisible = true" :disabled="isBtnDisable" type="primary" size="mini">添加属性</el-button>
          <el-table
            :data="onlyTableList"
            stripe
            border
            style="width: 100%">
            <el-table-column
              type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  @close="removeTag(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  style="width: 120px"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column
              type="index"
              label="#">
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
              <el-button  @click="editParams(scope.row.attr_id)" size="mini" type="primary" icon="el-icon-edit">修改</el-button>
              <el-button @click="delParams(scope.row.attr_id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数和添加属性的公用对话框 -->
      <el-dialog
        @close="resetparamsForm"
        :title="this.activeName==='many'?'添加动态参数':'添加静态属性'"
        :visible.sync="paramsDialogVisible"
        width="50%">
        <el-form ref="addParamsFormRef" :rules="addParamsFormRules" :model="addParamsForm" label-width="80px">
          <el-form-item :label="this.activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="paramsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParamsSub">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑参数公用对话框 -->
      <el-dialog
        @close="resetEditParamsForm"
        :title="this.activeName==='many'?'编辑动态参数':'编辑静态属性'"
        :visible.sync="editparamsDialogVisible"
        width="50%">
        <el-form ref="editParamsFormRef" :rules="addParamsFormRules" :model="editParamsForm" label-width="80px">
          <el-form-item :label="this.activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editparamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParamsSub">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      catesList: [],
      catesProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name'
      },
      casderValue: [],
      activeName: 'many',
      manyTableList: [],
      onlyTableList: [],
      paramsDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editparamsDialogVisible: false,
      editParamsForm: {
        attr_name: ''
      },
      inputVisible: false,
      inputValue: ''
    }
  },

  created () {
    this.getGoodsCate()
  },

  methods: {
    // 获取商品分类
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.catesList = res.data
    },
    // 获取动态参数/静态属性
    async getParams () {
      // 发送请求
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('请求参数失败')
      // 对attr_vals重新赋值
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data)
      if (this.activeName === 'many') this.manyTableList = res.data
      else this.onlyTableList = res.data
    },
    // 级联选择器发生变化
    casderHandleChange () {
      // console.log(this.casderValue)
      if (this.casderValue.length !== 3) {
        this.casderValue = []
        if (this.activeName === 'many') this.manyTableList = []
        else this.onlyTableList = []
      } else {
        this.getParams()
      }
    },
    // 点击tabs发送变化
    handleClick () {
      if (this.cateId) {
        this.getParams()
      }
    },
    // 点击确定添加参数&属性
    addParamsSub () {
      this.$refs.addParamsFormRef.validate(async flag => {
        if (!flag) return
        // 添加动态参数或者静态属性
        const { data: res } = await this.$axios.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.paramsDialogVisible = false
        this.getParams()
      })
    },
    resetparamsForm () {
      this.$refs.addParamsFormRef.resetFields()
    },
    async editParams (attrId) {
      // console.log(attrId)
      this.editparamsDialogVisible = true
      const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status === 200) {
        this.editParamsForm = res.data
      }
    },
    resetEditParamsForm () {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 点击确定编辑参数
    async editParamsSub () {
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
        attr_name: this.editParamsForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.$message.success('修改成功')
      this.editparamsDialogVisible = false
      this.getParams()
    },
    // 删除参数
    delParams (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除参数失败')
        this.$message.success('删除参数成功')
        this.getParams()
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    async setAttribute (row) {
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    },
    // 敲回车或者失去焦点
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        console.log('做添加的功能')
        row.attr_vals.push(row.inputValue)
        row.inputValue = ''
        row.inputVisible = false
        this.setAttribute(row)
      }
    },

    showInput (row) {
      // 代码走到这一行，仅代表数据已经改变了 页面在异步同步
      row.inputVisible = true
      // 数据驱动 代码
      // 代表当前组件页面已经更新完成了
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    removeTag (i, row) {
      row.attr_vals.splice(i, 1)
      this.setAttribute(row)
    }
  },

  computed: {
    // 是否禁用
    isBtnDisable () {
      if (this.casderValue.length !== 3) return true
      return false
    },
    // 分类Id
    cateId () {
      if (this.casderValue.length === 3) return this.casderValue[2]
      return null
    }
  }
}
</script>

<style scoped lang='less'>
.el-tag {
 margin-right: 10px;
}
</style>
